<template>
  <div class="artis-container" ref="parent" @click="showMenu = false">
    <div class="artis-top">
      <div class="artis-search">
        <el-input
          placeholder="请输入你要搜索的艺术家"
          v-model="queryParams.key"
          @keyup.native.enter="search"
          size="small"
          @clear="search"
          clearable
        ></el-input>
        <el-select
          v-model="queryParams.type"
          clearable
          @change="typeChange"
          class="search-select"
          placeholder="请选择"
          size="small"
        >
          <el-option
            v-for="item in typeAttrList"
            :key="item.data_id"
            :label="item.name"
            :value="item.data_id"
          ></el-option>
        </el-select>

        <el-select v-model="optionValue" @change="typeChange" class="search-select" placeholder="请选择" size="small">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </div>
      <div class="artis-btn"><el-button type="primary" size="small" @click="isShowDialog = true">新增</el-button></div>
    </div>

    <el-scrollbar style="height: calc(100vh - 190px)" class="scrollbar" id="scroll-bar">
      <el-table :data="list" @row-contextmenu="contextMenu" @expand-change="expandChange">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :gutter="20">
              <el-col :span="2" :offset="10"><div style="text-align: center; font-size: 16px">视频</div></el-col>
              <el-col :span="2" :offset="10">
                <div>
                  <el-button type="primary" size="small" @click="addSub(scope.row)">新增</el-button>
                </div>
              </el-col>
            </el-row>
            <el-table :data="scope.row.Videos">
              <el-table-column label="视频名称" prop="video_name">
                <template slot-scope="subScope">
                  <el-link type="primary">{{ subScope.row.video_name }}</el-link>
                </template>
              </el-table-column>
              <el-table-column label="视频介绍" prop="video_comment">
                <template slot-scope="subScope">
                  <el-link type="primary">{{ subScope.row.video_comment }}</el-link>
                </template>
              </el-table-column>
              <el-table-column label="视频时间" prop="video_date">
                <template slot-scope="subScope">
                  <el-link type="primary">{{ subScope.row.video_date }}</el-link>
                </template>
              </el-table-column>
              <el-table-column label="访问次数" prop="view_times"></el-table-column>
              <el-table-column label="收藏数" prop="collect_times"></el-table-column>
              <el-table-column label="操作" width="520">
                <template slot-scope="scope">
                  <el-upload
                    action="/ws"
                    class="avatar-uploader"
                    style="width: 90px; float: left"
                    :show-file-list="false"
                    :before-upload="
                      (file) => {
                        subBeforeAvatarUpload(file, scope.row.data_id, 'Works');
                      }
                    "
                  >
                    <el-button size="mini">上传封面</el-button>
                  </el-upload>
                  <el-button
                    size="mini"
                    style="width: 90px; float: left; margin-right: 10px"
                    @click="download(scope.row)"
                  >
                    下载封面
                  </el-button>
                  <el-upload
                    action="/ws"
                    class="avatar-uploader"
                    style="width: 90px; float: left"
                    :show-file-list="false"
                    :before-upload="
                      (file) => {
                        subBeforeAvatarUploadVideo(file, scope.row.data_id);
                      }
                    "
                  >
                    <el-button size="mini">上传视频</el-button>
                    <el-progress
                      v-if="videoFlag && uploadVideoId == scope.row.data_id"
                      :percentage="videoUploadPercent"
                      style="margin-top: 30px"
                    ></el-progress>
                  </el-upload>
                  <el-button type="primary" @click="subUpd(scope.row)" size="mini">修改</el-button>
                  <el-button type="danger" @click="subDel(scope.row.data_id)" size="mini">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <paging ref="VideosPage" :func="getVideos"></paging>
          </template>
        </el-table-column>
        <el-table-column label="id" prop="data_id"></el-table-column>
        <el-table-column label="背景图片">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.photo"
              style="width: 100px; height: 40px"
              :src="scope.row.photo"
              :preview-src-list="[scope.row.photo]"
              fit="cover"
            ></el-image>
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="艺术家名称" prop="name"></el-table-column>
        <el-table-column label="类型" prop="type">
          <template slot-scope="scope">
            <span>{{ artisType(scope.row.type) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="邮箱" prop="email"></el-table-column>

        <el-table-column label="最后修改时间" width="160" prop="data_update_time"></el-table-column>
        <el-table-column label="是否推荐" prop="association_job">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.recommend"
              @change="onRecommend(scope.row)"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template slot-scope="scope">
            <el-upload
              action=""
              class="avatar-uploader"
              style="width: 66px; float: left"
              :show-file-list="false"
              :before-upload="
                (file) => {
                  beforeAvatarUpload(file, scope.row.data_id);
                }
              "
            >
              <el-button size="mini">上传</el-button>
            </el-upload>
            <el-button type="primary" @click="updArtis(scope.row.data_id, scope.row)" size="mini">修改</el-button>
            <el-button type="danger" @click="delArtis(scope.row.data_id)" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>

    <paging ref="page" :func="getList"></paging>

    <el-dialog @closed="onClose" title="艺术家" :visible.sync="isShowDialog">
      <el-form :model="dataParams" :rules="rules" ref="dataParams" label-width="120px" class="demo-dataParams">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dataParams.name"></el-input>
        </el-form-item>
        <el-form-item label="是否推荐" prop="recommend">
          <el-switch v-model="dataParams.recommend" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="是否仅本人可见" prop="cellphone_hide">
          <el-switch v-model="dataParams.cellphone_hide" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>

        <el-form-item label="艺术家类型" prop="type">
          <el-select filterable v-model="dataParams.type">
            <el-option
              v-for="item in typeAttrList"
              :key="item.data_id"
              :value="item.data_id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="dataParams.gender">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系方式" prop="cellphone">
          <el-input v-model="dataParams.cellphone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="dataParams.email"></el-input>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input type="textarea" v-model="dataParams.position"></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="introduction">
          <el-input type="textarea" v-model="dataParams.introduction"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowDialog = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog @closed="onClose" title="视频" :visible.sync="VideosEditor">
      <el-form :model="VideosParams" :rules="VideosRules" ref="VideosParams" label-width="80px" class="demo-dataParams">
        <el-form-item label="视频名称" prop="video_name">
          <el-input v-model="VideosParams.video_name"></el-input>
        </el-form-item>
        <el-form-item label="视频时间" prop="video_date">
          <el-date-picker
            v-model="VideosParams.video_date"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="视频说明" prop="video_comment">
          <el-input v-model="VideosParams.video_comment"></el-input>
        </el-form-item>
        <el-form-item label="视频详细信息" prop="video_detail">
          <el-input v-model="VideosParams.video_detail"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="VideosEditor = false">取 消</el-button>
        <el-button type="primary" @click="subDialogConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <div class="menu" ref="menu" v-show="showMenu">
      <div @click="move('up')">前移</div>
      <div @click="move('down')">后移</div>
      <div @click="move('top')">置顶</div>
      <div @click="move('bottom')">置底</div>
    </div>
  </div>
</template>

<script>
  import _ from 'lodash';
  import paging from '@/components/paging';
  import artisManage from '@/api/artis';
  import typeManage from '@/api/type';
  import { getImageUrl } from '@/utils/image';
  import Vue from 'vue';
  import { qiniuUploadFile } from '@/utils/QiniuUpload';

  var checkEmail = (rule, value, callback) => {
    const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
    if (!value) {
      callback();
    }
    setTimeout(() => {
      if (mailReg.test(value)) {
        callback();
      } else if (value) {
        callback(new Error('请输入正确的邮箱格式'));
      }
    }, 100);
  };
  var checkPhone = (rule, value, callback) => {
    const mailReg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
    if (!value) {
      return callback(new Error('联系方式不能为空'));
    }
    setTimeout(() => {
      if (mailReg.test(value)) {
        callback();
      } else {
        callback(new Error('请输入正确的联系方式'));
      }
    }, 100);
  };

  export default {
    name: 'artis-view',
    components: {
      paging,
    },
    data() {
      return {
        list: [],
        queryParams: {
          key: '',
        },
        options: [
          {
            value: 'all',
            label: '所有艺术家',
          },
          {
            value: 'recommend',
            label: '推荐艺术家',
          },
        ],
        optionValue: 'all',
        dataParams: {
          name: '', //姓名
          position: '', //职位
          gender: '男', //性别
          type: '', //类型
          introduction: '', //介绍
          email: '', //邮箱
          cellphone_hide: false, //是否仅本人可见
          recommend: false, //是否推荐
        },
        typeList: [],
        typeAttrList: [],
        typeAttrAllList: [],
        isShowDialog: false,
        updId: '',
        rules: {
          name: [{ required: true, message: '请输入艺术家名称', trigger: 'blur' }],
          type: [{ required: true, message: '请输入艺术类型', trigger: 'change' }],
          email: [{ required: false, trigger: 'blur', validator: checkEmail }],
          // cellphone: [{ required: true, trigger: 'blur', validator: checkPhone }],
        },
        showMenu: false,

        VideosRules: {
          video_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          video_comment: [{ required: true, message: '请输入说明', trigger: 'blur' }],
          video_date: [{ required: true, message: '请选择时间', trigger: 'change' }],
          video_detail: [{ required: true, message: '请输入详细信息', trigger: 'blur' }],
        },
        VideosParams: {
          video_name: '',
          video_date: '',
          video_comment: '',
          video_detail: '',
        },
        VideosEditor: false,
        activeR: null,
        videoUpd: '',

        videoFlag: false,
        uploadVideoId: '',
        videoUploadPercent: 0,
      };
    },
    async mounted() {
      let res = await typeManage.getType({ parent_id: -1 });
      this.typeList = res.item_list.filter((item) => {
        return item.parent_id === -1;
      });
      let resAttr = await typeManage.getArtType({ art_type: 1 });
      console.log('res', resAttr);

      this.typeAttrAllList = resAttr.item_list;
      this.typeAttrList = resAttr.item_list.filter((item) => {
        return item.parent_id === -1;
      });
      this.refresh();
    },
    computed: {},
    methods: {
      async move(type) {
        await artisManage.moveRecomment(this.menuId, 'move_' + type);
        this.showMenu = false;
        this.$refs.page.refresh();
      },
      contextMenu(r, column, e) {
        if (this.optionValue === 'recommend') {
          let rect = this.$refs.parent.getBoundingClientRect();
          this.$refs.menu.style.top = e.clientY - rect.top + 'px';
          this.$refs.menu.style.left = e.clientX - rect.left + 'px';
          this.showMenu = true;
          this.menuId = r.data_id;
          e.preventDefault();
        }
      },
      getImageUrl,
      refresh() {
        this.$refs.page.refresh();
      },
      search() {
        this.$refs.page.search();
      },
      artisType(type) {
        let obj = this.typeAttrAllList.find((item) => {
          return item.data_id === type;
        });
        return obj?.name || '';
      },
      typeChange() {
        this.$refs.page.refresh();
      },
      async getList(callback) {
        let res;
        if (this.optionValue === 'recommend') {
          res = await artisManage.getRecommentArtis(this.queryParams);
        } else {
          res = await artisManage.getArtis(this.queryParams);
        }
        let total = res.total_count;
        this.list = res.item_list.map((m) => {
          m.Videos = [];
          return m;
        });
        callback(this.list, total);
      },
      async beforeAvatarUpload(file, id) {
        const formData = new FormData();
        formData.append('上传的key值', file);

        let res = await qiniuUploadFile(file, 'artis');
        if (res) {
          await artisManage.updArtis(id, { photo: res.key });
          this.refresh();
        }
      },
      async onRecommend(row) {
        await artisManage.updArtis(row.data_id, row);
        this.refresh();
      },
      updArtis(data_id, row) {
        this.dataParams = _.cloneDeep(row);
        this.dataParams.gender = this.dataParams.gender ? '男' : '女';
        this.updId = data_id;
        this.isShowDialog = true;
      },
      async delArtis(data_id) {
        this.$alert('是否确定删除该艺术家', '删除', {
          confirmButtonText: '确定',
          callback: async (action) => {
            if (action === 'confirm') {
              await artisManage.delArtis(data_id);
              this.refresh();
            }
          },
        });
      },
      async dialogConfirm() {
        this.$refs.dataParams.validate(async (valid) => {
          if (valid) {
            let res = null;
            if (this.updId) {
              res = await artisManage.updArtis(this.updId, {
                ...this.dataParams,
                recommend: Number(this.dataParams.recommend),
                gender: this.dataParams.gender === '男' ? 1 : 0,
                type: this.dataParams.type.length
                  ? this.dataParams.type[this.dataParams.type.length - 1]
                  : this.dataParams.type,
              });
            } else {
              res = await artisManage.setArtis({
                ...this.dataParams,
                recommend: Number(this.dataParams.recommend),
                gender: this.dataParams.gender === '男' ? 1 : 0,
                type: this.dataParams.type.length
                  ? this.dataParams.type[this.dataParams.type.length - 1]
                  : this.dataParams.type,
              });
            }
            if (res) {
              this.isShowDialog = false;
              this.updId = '';
              this.refresh();
            }
          }
        });
      },
      onClose() {
        this.updId = '';
        this.dataParams = {
          name: '', //姓名
          recommend: false, //是否推荐
          type: '', //类型
          introduction: '', //介绍
          gender: '男', //性别
          nation: '', //民族
          email: '', //邮箱
        };
      },
      expandChange(r) {
        this.activeR = r;
        this.$nextTick((_) => {
          this.$refs.VideosPage?.refresh();
        });
      },
      async getVideos(callback) {
        let res = await artisManage.getVideos({ art_id: this.activeR.data_id });
        this.activeR.Videos = res.item_list;
        callback(res.item_list, res.total_count);
      },
      addSub(r) {
        this.VideosEditor = true;
      },
      subUpd(r) {
        this.videoUpd = r.data_id;
        this.VideosEditor = true;
        this.VideosParams = {
          ...r,
          video_date: r.video_date.length > 12 ? r.video_date : r.video_date + ' 00:00:00',
        };
      },
      async subDialogConfirm() {
        if (this.videoUpd) {
          await artisManage.UpdVideos(this.videoUpd, this.VideosParams);
        } else {
          await artisManage.createVideos({ art_id: this.activeR.data_id, ...this.VideosParams });
        }
        this.VideosEditor = false;
        this.videoUpd = '';
        this.VideosParams = {
          video_name: '',
          video_date: '',
          video_comment: '',
          video_detail: '',
        };
        this.$refs.VideosPage?.refresh();
      },
      async subBeforeAvatarUpload(file, id) {
        let res = await qiniuUploadFile(file, 'artis');
        if (res) {
          await artisManage.UpdVideos(id, { video_page: res.key });
          this.$refs.VideosPage?.refresh();
          this.$message.success('上传成功');
        }
      },
      async subBeforeAvatarUploadVideo(file, id) {
        this.uploadVideoId = id;
        this.videoUploadPercent = 0;
        this.videoFlag = true;

        const timer = setInterval(() => {
          if (this.videoUploadPercent >= 99) {
            this.videoUploadPercent = 100;
            this.videoFlag = false;
            clearInterval(timer);
            return;
          }
          this.videoUploadPercent += 1;
        }, 20);

        let res = await qiniuUploadFile(file, 'artis');
        if (res) {
          await artisManage.UpdVideos(id, { video_path: res.key });
          this.$refs.VideosPage?.refresh();
          this.$message.success('上传成功');
        }

        // const formData = new FormData();
        // formData.append('上传的key值', file);
        // await artisManage[`uploadVideo`](id, formData);
        // this.$refs.VideosPage?.refresh();
        // this.$message.success('上传成功');

        clearInterval(timer);
        this.uploadVideoId = '';
        this.videoUploadPercent = 0;
        this.videoFlag = false;
      },
      async download(r) {
        let blob = await artisManage.download(r.data_id);
        const url = window.URL.createObjectURL(new Blob([blob]));
        const link = document.createElement('a');
        link.href = url;
        let names = `2324/2434/aqq.mp4`.split('/');
        link.setAttribute('download', names[names.length - 1]);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      },
      async downloadVideo(r) {
        let info = await artisManage.getVideoInfo(r.data_id);
        let blob = await artisManage.downloadVideo(info.video_path);
        const url = window.URL.createObjectURL(new Blob([blob]));
        const link = document.createElement('a');
        link.href = url;
        let names = `2324/2434/aqq.mp4`.split('/');
        link.setAttribute('download', names[names.length - 1]);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      },
      async subDel(id) {
        this.$alert('是否确定删除？', '删除', {
          confirmButtonText: '确定',
          callback: async (action) => {
            if (action === 'confirm') {
              await artisManage.delVideo(id);
            }
          },
        });
      },
    },
  };
</script>

<style lang="less" scoped>
  .menu {
    position: absolute;
    top: 0;
    left: 0;
    background-color: white;
    border-radius: 10px;
    box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.3);
    overflow: hidden;
    z-index: 999;
    & > div {
      padding: 10px 40px;
      border-bottom: 1px solid #eee;
      &:last-child {
        border-bottom: none;
      }
      &:hover {
        cursor: pointer;
        background-color: #409eff;
        color: white;
      }
    }
  }
  .artis-container {
    height: 100%;
    .artis-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .artis-search {
        display: flex;
        .search-select {
          margin-left: 12px;
        }
      }
    }
  }
</style>
